<template>
  <div class="toolbar colorMain">
    <el-header class="mt-10">
      <el-form :inline="true" size="small">
        <el-form-item label="" >
          <span style="font-weight: bold;font-size: 18px">{{ data.event_name }}</span>
        </el-form-item>
        <el-form-item label="展示单位" label-width="100px">
          <el-radio-group v-model="intervalType" size="small" @change="change">
            <el-radio-button label="hour">时</el-radio-button>
            <el-radio-button label="day">天</el-radio-button>
            <el-radio-button label="week">周</el-radio-button>
            <el-radio-button label="month">月</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时间" label-width="80px">
          <el-date-picker
            v-model="pickTime"
            :picker-options="pickerOptions"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
            size="small"
            @change="chooseDate"/>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <div class="block d2-mb-20">
        <span class="demonstration">{{ typeText[event_id] }}</span>
        <el-cascader
          v-model="selectModel"
          :options="selectOptions"
          placeholder="选择"
          filterable
          size="small"
          change-on-select
          style="width: 280px"
          @change="handleChange"
        />
      </div>
      <div class="mt-10">数据走势</div>
      <ve-line :data="chartData" />
      <div class="mt-10 mb-10">数据汇总</div>
      <el-table :data="tableData" style="width: 100%" size="small" stripe border fit highlight-current-row @cell-click="cellClick" >
        <template v-for="(item, index) in key_mapper">
          <el-table-column v-if="item.is_percentage" :key = "index" :prop="item.value" :label="item.name" :min-width="110" :formatter="formatter" sortable>
            <template slot-scope="scope">{{ `${scope.row[item.key]}%` }}</template>
          </el-table-column>
          <el-table-column v-else :key = "index" :prop="item.value" :label="item.name" :min-width="120" :formatter="formatter" sortable/>
        </template>
      </el-table>
      <div v-if="chartDataPie.rows.length" class="mt-10 mb-10">饼图</div>
      <ve-pie :data="chartDataPie" :settings="chartPieSettings"/>
    </el-main>
  </div>
</template>

<script>
import { eventAnalysis, getEventDistribution } from '@/api/table'
import { pickerOptions } from '@/model/DateRange'
import dayjs from 'dayjs'
import { fixed3 } from '@/utils'

export default {
  name: 'Page1',
  data() {
    // this.chartSettings = {
    //   axisSite: { right: ['利润率'] },
    //   yAxisType: ['normal', 'normal'],
    //   yAxisName: ['金额', '实际利润率']
    // }
    this.chartPieSettings = {
      limitShowNum: 15
    }
    return {
      chartDataPie: {
        columns: ['key', 'value'], rows: []
      },
      typeText: { 'cp_lottery': '彩种 / 玩法类别', recharge: '充值类型', withdraw: '提现类型' },
      selectModel: [],
      data: { event_name: '购彩分析' },
      chartData: {
        columns: [], rows: []
      },
      tableData: [],
      key_mapper: [],
      intervalType: 'day',
      pickTime: [dayjs().subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss')],
      event_id: this.$route.meta.event_id,
      selectOptions: [],
      nested_path_list: [],
      order: [],
      selectedValue: '',
      dateList: [],
      pickerOptions: pickerOptions,
      dataPie: []
    }
  },
  created() {
    this.getData().then(() => {
      this.selectModel = [this.selectOptions[0].value]
      this.handleChange(this.selectModel)
    })
  },
  methods: {
    getData() {
      const data = {
        event_id: this.event_id,
        interval_type: this.intervalType,
        time_range: JSON.stringify(this.pickTime),
        nested_path_list: JSON.stringify(this.nested_path_list)
      }
      this.$loading({ lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.15)' })
      return eventAnalysis(data).then(res => {
        this.chartDataPie.rows = []
        this.data = res.data
        if (res.data.list.length === 0) {
          return
        }
        this.selectOptions = res.data.group_mapper
        this.key_mapper = [{ name: '日期', value: 'date' }, { name: '次数', value: 'pv' }, { name: '人数', value: 'uv' }, ...res.data.key_mapper]
        this.chartData.columns = ['日期', ...res.data.key_mapper.map(item => item.name)]
        this.chartData.rows = res.data.list.map(item => {
          return this.dealData(item)
        }).reverse()
        this.tableData = res.data.list.map(item => {
          return this.dealtableData(item)
        })
      }, err => {
        this.$message({ type: 'error', message: err.response.data.msg })
      })
    },
    dealtableData(item) {
      let fiterData = {}
      const filter = {}
      this.data.key_mapper.forEach(item => {
        filter[item.value] = item.name
      })
      for (const key of Object.keys(item.data)) {
        if (filter[key]) {
          fiterData[key] = item.data[key].sum
        }
      }
      fiterData = Object.assign({ date: item.base_time }, { 'report_id': item._id }, { 'uv': item.data.uv }, { 'pv': item.data.pv }, fiterData)
      return fiterData
    },
    dealData(item) {
      let fiterData = {}
      const filter = {}
      this.data.key_mapper.forEach(item => {
        filter[item.value] = item.name
      })
      for (const key of Object.keys(item.data)) {
        if (filter[key]) {
          fiterData[filter[key]] = item.data[key].sum
        }
      }
      fiterData = Object.assign({ '日期': item.base_time }, fiterData)
      return fiterData
    },
    handleChange(val) {
      this.nested_path_list = []
      if (val.length % 2 === 0) {
        for (let i = 0; i < val.length / 2; i++) {
          const obj = {
            key: val[i * 2],
            value: val[i * 2 + 1]
          }
          this.nested_path_list.push(obj)
        }
        this.getData()
      } else {
        const arr = [...val, '']
        for (let i = 0; i < arr.length / 2; i++) {
          const obj = {
            key: val[i * 2],
            value: val[i * 2 + 1]
          }
          this.nested_path_list.push(obj)
        }
        // debugger
      }
    },
    showpie(data) {
      this.chartDataPie.rows = data
    },
    cellClick(row, column, cell, event) {
      if (['date'].includes(column.property)) {
        return
      }
      if (this.nested_path_list[this.nested_path_list.length - 1].value) {
        return
      }
      const data = {
        event_id: this.event_id,
        interval_type: this.intervalType,
        nested_path_list: JSON.stringify(this.nested_path_list),
        report_id: row.report_id,
        value_field: column.property
      }
      getEventDistribution(data).then(res => {
        this.showpie(res.data)
      }, err => {
        this.$message({ type: 'error', message: err.response.data.msg })
      })
    },
    change(value) {
      this.getData()
    },
    chooseDate(val) {
      // debugger
      // this.pickTime = val
      this.getData()
    },
    formatter(row, column, item) {
      return fixed3(item)
    }
  }
}
</script>

